package ext.tianma.bom.eco;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ext.com.core.CoreUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.bom.bean.BOMBean;
import ext.tianma.bom.bean.ECOBean;
import ext.tianma.bom.service.TMECOUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.bom.util.StringUtil;
import ext.tianma.number.util.PartUtil;
import ext.tianma.part.MyPartUtil;
import ext.tianma.project.LWCUtil;
import wt.change2.WTChangeOrder2;
import wt.fc.ObjectNoLongerExistsException;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.collections.WTCollection;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.httpgw.URLFactory;
import wt.identity.IdentityFactory;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.method.MethodContext;
import wt.org.WTUser;
import wt.part.LineNumber;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.WTPart;
import wt.part.WTPartHelper;
import wt.part.WTPartMaster;
import wt.part.WTPartSubstituteLink;
import wt.part.WTPartUsageLink;
import wt.pds.StatementSpec;
import wt.pom.Transaction;
import wt.pom.WTConnection;
import wt.query.KeywordExpression;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.team.TeamReference;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.util.WTRuntimeException;
import wt.vc.OneOffVersionIdentifier;
import wt.vc.OneOffVersionInfo;
import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;

/**
 * 用于BOM变更操作
 * 
 * @author GaoJinWang
 * 
 */
public class BOMHelp {
	private static final Logger log = LogR.getLogger(BOMHelp.class.getName());
	public static final String correctcode = "000";
	public static final String errorcode = "001";
	public static String effectpartname = "受影响对象";
	public static String addpartname = "新增料";
	public static String delectpartname = "删除料";
	public static String oldpartname = "原料";
	public static String newpartname = "新料";
	public static String mainpartname = "主料";
	public static String changepartname = "变更料";
	public static String newaddreplacepartname = "新增替代料";
	public static String delreplacepartname = "删除替代料";
	public static String oldreplacepartname = "原替代料";
	public static String newreplacepartname = "新替代料";
	public static String oldmainpartname = "原主料";
	public static String newmainpartname = "新主料";
	public static ReferenceFactory REF_FACTORY = new ReferenceFactory();

	public static String getOid(Persistable p) throws Exception {
		return REF_FACTORY.getReferenceString(p);
	}

	public static void main(String[] args) {
		try {
			JSONObject ob = new JSONObject();
			String a = null;
			ob.put("222", a);
			ob.put("123", a);
			ob.put("321", a);
			log.info(ob);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	/**
	 * 根据编号查询受影响对象BOM
	 * 
	 * 正确返回格式为： { tmCode:"000", dataList:[{
	 * number:"E001",view:"A10",state:"正在工作"}, {
	 * number:"E001",view:"A10",state:"正在工作"} ] length:2 }
	 * 
	 * @param number
	 * @return
	 */
	public static String queryEffectPart(JSONArray array) {
		// 视图
		String view = "";
		// 状态
		String state = "";
		// 版本
		String version = "";
		String result = "";
		JSONArray dataarray = new JSONArray();
		JSONObject resultobject = new JSONObject();
		JSONObject object;
		try {
			List<WTPart> plist = new ArrayList<WTPart>();
			try {
				for (int i = 0; i < array.length(); i++) {
					List<WTPart> list = new ArrayList<WTPart>();
					JSONObject ob = (JSONObject) array.get(i);

					String number = ob.getString("partnumber");
					String requestview = "";
					if (ob.has("view")) {
						requestview = ob.getString("view");
					}
					WTPart part111 = PartUtil.getWTPartByNumber(number);
					if (part111 != null) {
						String softType = GenericUtil.getTypeId(part111);
						String softname = GenericUtil.getTypeName(part111);
						log.info("====part softtype====" + softType);
						log.info("====part softname====" + softname);
						// GenericUtil.getTypeName(part111);
						/*
						 * if (softType.indexOf("cn.tianma.FinishedGood") != -1
						 * || softType.indexOf("cn.tianma.SemiFinishedGood") !=
						 * -1) {
						 */
						String partstate = part111.getState().getState().getDisplay(Locale.CHINA);
						/*
						 * if("正在工作".equals(partstate) || "新品".equals(partstate)
						 * || "试产".equals(partstate) || "风险批量".equals(partstate)
						 * || "小批量".equals(partstate) ||
						 * "量产发布".equals(partstate)){
						 */
						log.info("=====view:" + part111.getViewName() + "========version:"
								+ VersionControlHelper.getIterationDisplayIdentifier(part111).toString());
						if (!isNullOrEmpty(requestview)) {
							part111 = GenericUtil.getPart(number, "", requestview);
							if (part111 != null && !list.contains(part111)) {
								list.add(part111);
							}
						} else {
							list = getAllLatestVersionPart(number.trim());
						}

						for (WTPart part : list) {
							partstate = part.getState().getState().getDisplay(Locale.CHINA);
							if ("正在工作".equals(partstate) || "新品".equals(partstate) || "试产".equals(partstate)
									|| "风险批量".equals(partstate) || "小批量".equals(partstate)
									|| "量产发布".equals(partstate)) {
								if(!plist.contains(part)){
									plist.add(part);
								}
							} else {
								result += number + "视图" + part.getViewName() + "的状态为" + partstate + ",不符合变更的状态";
							}
						}
						/*
						 * }else{ result +=number+"的状态为"+partstate+",不符合变更的状态";
						 * }
						 */

						/*
						 * } else { result += number + "不是成品或半成品"; }
						 */
					} else {
						result += number + "不存在";
					}

					// 不取关系 只取当前搜索的料号/受影响对象 视图
					/*
					 * for (WTPart part : list) { getParentParts(part, plist); }
					 */
				}

				for (WTPart part : plist) {
					object = new JSONObject();
					view = part.getViewName();
					if (!"design".equalsIgnoreCase(view)) {
						state = part.getState().getState().getDisplay();
						version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
						object.put("number", part.getNumber());
						object.put("state", state);
						object.put("view", part.getViewName());
						object.put("version", version);
						log.info("======object========" + object.toString());
						dataarray.put(object);
					}
				}
			} catch (Exception e) {

			}

			resultobject.put("tmCode", correctcode);
			resultobject.put("datalist", dataarray);
			resultobject.put("result", result);
			resultobject.put("length", dataarray.length());

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return resultobject.toString();
	}

	/**
	 * 根据编号查询受影响对象BOM
	 * 
	 * 正确返回格式为： { tmCode:"000", dataList:[{
	 * number:"E001",view:"A10",state:"正在工作"}, {
	 * number:"E001",view:"A10",state:"正在工作"} ] length:2 }
	 * 
	 * @param number
	 * @return
	 */
	public static String queryMutiEffectPart(JSONArray array) {
		// 视图
		String view = "";
		// 状态
		String state = "";
		// 版本
		String version = "";
		String result = "";
		JSONArray dataarray = new JSONArray();
		JSONObject resultobject = new JSONObject();
		JSONObject object;
		List<WTPart> list = new ArrayList<WTPart>();
		try {
			// 父层物料 或 自身不同视图
			List<WTPart> plist = new ArrayList<WTPart>();
			try {
				for (int i = 0; i < array.length(); i++) {
					JSONObject ob = (JSONObject) array.get(i);
					String number = ob.getString("partnumber");
					String requestview = "";
					if (ob.has("view")) {
						requestview = ob.getString("view");
					}
					if (!StringUtil.isNullOrEmpty(number)) {
						WTPart part111 = PartUtil.getWTPartByNumber(number);
						if (part111 != null) {
							String typeid = GenericUtil.getTypeId(part111);

							String softType = GenericUtil.getTypeId(part111);
							String softname = GenericUtil.getTypeName(part111);
							log.info("====part softtype====" + softType);
							log.info("====part softname====" + softname);
							// GenericUtil.getTypeName(part111);
							if (!isNullOrEmpty(requestview)) {
								part111 = GenericUtil.getPart(number, "", requestview);
								if (part111 != null) {
									list.add(part111);
								}
							} else {
								list = getAllLatestVersionPart(number.trim());
							}

							/*
							 * if (softType.indexOf("cn.tianma.FinishedGood") !=
							 * -1 ||
							 * softType.indexOf("cn.tianma.SemiFinishedGood") !=
							 * -1) { String partstate =
							 * part111.getState().getState().getDisplay(Locale.
							 * CHINA); log.info("=====view:" +
							 * part111.getViewName() + "========version:" +
							 * VersionControlHelper.
							 * getIterationDisplayIdentifier(part111).toString()
							 * ); for (WTPart part : list) { partstate =
							 * part.getState().getState().getDisplay(Locale.
							 * CHINA); if ("正在工作".equals(partstate) ||
							 * "新品".equals(partstate) || "试产".equals(partstate)
							 * || "风险批量".equals(partstate) ||
							 * "小批量".equals(partstate) ||
							 * "量产发布".equals(partstate)) { plist.add(part); }
							 * else { result += part.getNumber() + "视图" +
							 * part.getViewName() + "的状态为" + partstate +
							 * ",不符合变更的状态"; } }
							 * 
							 * } else { // result += number + "不是成品或半成品"; for
							 * (WTPart part : list) { plist =
							 * getParentParts(part, plist); } }
							 */
							// 本次父层物料
							List<WTPart> parentlist = new ArrayList<WTPart>();
							for (WTPart part : list) {
								parentlist = getParentParts(part, plist, requestview);
							}
							if (parentlist.size() == 0 && (typeid.indexOf("cn.tianma.FinishedGood") != -1
									|| typeid.indexOf("cn.tianma.SemiFinishedGood") != -1)) {
								plist.addAll(list);
							}
						} else {
							result += number + "不存在";
						}
					}

				}
				for (WTPart part : plist) {
					object = new JSONObject();
					view = part.getViewName();
					if (!"design".equalsIgnoreCase(view)) {
						state = part.getState().getState().getDisplay(Locale.CHINA);
						version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
						object.put("number", part.getNumber());
						object.put("state", state);
						object.put("view", part.getViewName());
						object.put("version", version);
						// log.info("======object========" + object.toString());
						dataarray.put(object);
					}
				}
			} catch (Exception e) {

			}

			resultobject.put("tmCode", correctcode);
			resultobject.put("datalist", dataarray);
			resultobject.put("result", result);
			resultobject.put("length", dataarray.length());

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return resultobject.toString();
	}

	/**
	 * 根据部件编号获取所有最新小版本
	 * 
	 */
	public static List<WTPart> getAllLatestVersionPart(String number) {
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPart.class);
			SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, number);
			qs.appendWhere(sc);
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
			QueryResult qr2 = PersistenceHelper.manager.find(qs);
			while (qr2.hasMoreElements()) {
				part = (WTPart) qr2.nextElement();
				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = ext.tianma.bom.eco.BOMHelp.getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				// log.info("view:" + part.getViewName() + "===version:" +
				// version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {

		}
		return list;

	}

	/**
	 * 新增物料数据校验
	 * 
	 * @return 返回数据格式：{tmCode:”000”，result：”***不存在”/”***存在”，dataList:[{
	 *         effectNum: ’’,view:””,}]}
	 */
	public static String addPartValidate(JSONArray array) {
		JSONObject obj = new JSONObject();
		JSONArray dataarray = new JSONArray();
		String newAddNum = "";// 新增物料号
		String EffectNum = "";// 受影响BOM号
		String View = "";
		String code = correctcode;
		String result = "";
		WTPart part = null;
		WTPart childpart = null;
		WTPart bompart = null;
		List<String> errornumber = new ArrayList<String>();
		try {
			for (int i = 0; i < array.length(); i++) {
				try {
					JSONObject ob = (JSONObject) array.get(i);
					newAddNum = ob.getString("newaddnum");
					EffectNum = ob.getString("effectnumber");
					View = ob.getString("view");
					String oid = ob.getString("ecoid");
					String amount = ob.getString("amount");

					String rowNmuber = "";
					if (ob.has("rowNmuber")) {
						rowNmuber = ob.getString("rowNmuber");
					}

					try {
						if (!isNullOrEmpty(amount)) {
							double a = Double.parseDouble(amount);
						}
					} catch (Exception e) {
						result += "第" + rowNmuber + "行" + "用量 " + amount + "不合法\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					part = PartUtil.getWTPartByNumber(newAddNum);
					childpart = GenericUtil.getPart(newAddNum, "", View);
					bompart = GenericUtil.getPart(EffectNum, "", View);
					if (childpart != null) {
						String state = childpart.getState().getState().getDisplay(Locale.CHINA);
						if ("废弃".equals(state)) {
							result += "第" + rowNmuber + "行" + addpartname + newAddNum + "状态为废弃，不能作为主料";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
					}
					// BOM是否存在
					if (bompart == null) {
						result += "第" + rowNmuber + "行" + effectpartname + EffectNum + "不存在\r";
					} else if (part == null) {
						// 新增物料号是否存在
						// obj.put("result", newAddNum + "不存在");
						result += "第" + rowNmuber + "行" + addpartname + newAddNum + "不存在\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else if (part != null && childpart == null) {
						result += "第" + rowNmuber + "行" + addpartname + newAddNum + "不存在" + View + "视图";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
						boolean flag = false;
						WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
						List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(EffectNum, eco.getNumber());
						// log.info("=========ecolist:" + ecolist.size());
						if (ecolist.size() != 0) {
							result += "第" + rowNmuber + "行" + effectpartname + EffectNum + "已存在于未关闭的ECO变更流程中("
									+ ecolist.toString() + ")\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
						// 新增物料号是否已经存在bom中
						List<String> linklist = new ArrayList<String>();
						QueryResult qs = WTPartHelper.service.getUsesWTPartMasters(bompart);
						while (qs.hasMoreElements()) {
							WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
							linklist.add(((WTPartMaster) link.getRoleBObject()).getNumber());
						}
						if (linklist.contains(newAddNum) && !"H10".equals(View)) {
							result += "第" + rowNmuber + "行" + addpartname + newAddNum + "已存在于" + effectpartname
									+ EffectNum + "\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						} else {
							// 返回的datalist中是有效的受影响对象
							JSONObject obj2 = new JSONObject();
							obj2.put("effectnumber", EffectNum);
							if (bompart != null) {
								obj2.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
								obj2.put("effectunit", bompart.getDefaultUnit());
							}

							obj2.put("view", View);
							if (childpart != null) {
								obj2.put("unit", childpart.getDefaultUnit());
								obj2.put("state", childpart.getState().getState().getDisplay(Locale.CHINA));
							}
							obj2.put("rowNmuber", rowNmuber);
							dataarray.put(obj2);
						}
					}

				} catch (Exception e) {
					// obj.put("tmCode", errorcode);
					code = errorcode;
					result += e.getMessage();
					// obj.put("result", "数据格式不正确" + e.getMessage());
					log.error(e.getMessage(), e);
				}
			}
			obj.put("datalist", dataarray);
		} catch (Exception e) {
			code = errorcode;
			result += e.getMessage();
			log.error(e.getMessage(), e);
		} finally {
			try {
				obj.put("tmCode", code);
				obj.put("result", result);
				obj.put("datalist", dataarray);
				obj.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}
		}
		return obj.toString();
	}

	/**
	 * 获取part第一层关系中的最大行号
	 * 
	 * @param pl
	 * @param item
	 */
	public static int getMaxLineNumber(WTPart part) {
		List<String> list = new ArrayList<String>();
		int max = 0;
		QueryResult qs;
		try {
			qs = WTPartHelper.service.getUsesWTPartMasters(part);
			while (qs.hasMoreElements()) {
				WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
				if (link.getLineNumber() != null) {
					if (!isNullOrEmpty(link.getLineNumber().toString())) {
						String linenumber = link.getLineNumber().toString();
						if (!list.contains(linenumber)) {
							list.add(linenumber);
						}
					}
				}
			}
			for (String linenum : list) {
				if (!isNullOrEmpty(linenum) && Integer.parseInt(linenum) > max) {
					max = Integer.parseInt(linenum);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return max;
	}

	/**
	 * 空或者NULL值时返回true
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str.equals("NULL"));
	}

	/**
	 * 删除物料数据校验
	 * 
	 * @return 返回数据格式：{tmCode:”000”，result：”***不存在”/”***存在”，dataList:[{
	 *         effectNum: ’’,view:””,}]}
	 */
	public static String deletePartValidate(JSONArray array) {
		JSONObject obj = new JSONObject();
		JSONArray dataarray = new JSONArray();
		String partnumber = "";// 物料号
		String EffectNum = "";// 受影响BOM号
		String View = "";
		String code = correctcode;
		String result = "";
		List<String> errornumber = new ArrayList<String>();

		WTPart part = null;
		WTPart bompart = null;
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject ob = (JSONObject) array.get(i);
				partnumber = ob.getString("partnumber");
				EffectNum = ob.getString("effectnumber");
				View = ob.getString("view");
				// ECO oid
				String oid = ob.getString("ecoid");

				String rowNmuber = "";
				if (ob.has("rowNmuber")) {
					rowNmuber = ob.getString("rowNmuber");
				}

				part = PartUtil.getWTPartByNumber(partnumber);
				bompart = GenericUtil.getPart(EffectNum, "", View);
				// BOM是否存在
				if (bompart == null) {
					result += "第" + rowNmuber + "行" + effectpartname + EffectNum + "不存在" + View + "视图\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}

				} else if (part == null) {
					// 物料号是否存在
					result += "第" + rowNmuber + "行" + delectpartname + partnumber + "不存在\r";
					part = GenericUtil.getPart(partnumber, "", View);
					if (part == null) {
						result += "第" + rowNmuber + "行" + delectpartname + partnumber + "不存在" + View + "视图;\r";
					}
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
					boolean flag = false;
					WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
					// ......................
					List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(EffectNum, eco.getNumber());
					if (ecolist.size() != 0) {
						result += "第" + rowNmuber + "行" + effectpartname + EffectNum + "已存在于未关闭的ECO变更流程中("
								+ ecolist.toString() + ")\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					// 物料号是否已经存在bom中
					Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
					Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
					QueryResult qs = WTPartHelper.service.getUsesWTPartMasters(bompart);
					while (qs.hasMoreElements()) {
						WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
						String linenumber = link.getLineNumber().toString();
						if (((WTPartMaster) link.getRoleBObject()).getNumber().equals(partnumber)) {
							linklist.put(((WTPartMaster) link.getRoleBObject()).getNumber(), link);
							linklist2.put(linenumber, link);
						}
					}

					if (!linklist.containsKey(partnumber)) {
						result += "第" + rowNmuber + "行" + delectpartname + partnumber + "不存在于" + effectpartname
								+ EffectNum + "\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						// 返回的datalist中是有效的受影响对象
						/*
						 * WTPartUsageLink link = linklist.get(partnumber);
						 * JSONObject obj2 = new JSONObject();
						 * obj2.put("effectnum", EffectNum); obj2.put("view",
						 * View); obj2.put("partnumber", partnumber);
						 * obj2.put("linenumber",
						 * link.getLineNumber().toString()); obj2.put("amount",
						 * link.getQuantity().getAmount()); dataarray.put(obj2);
						 */
						Iterator iter = linklist2.keySet().iterator();
						while (iter.hasNext()) {
							String linenumber = iter.next().toString();
							WTPartUsageLink link2 = linklist2.get(linenumber);

							JSONObject obj3 = new JSONObject();
							obj3.put("rowNmuber", rowNmuber);
							obj3.put("effectnum", EffectNum);
							if (bompart != null) {
								obj3.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
							}

							obj3.put("view", View);
							obj3.put("partnumber", partnumber);
							obj3.put("linenumber", linenumber);
							obj3.put("amount", link2.getQuantity().getAmount());
							obj3.put("unit", link2.getQuantity().getUnit());
							if (part != null) {
								obj3.put("state", part.getState().getState().getDisplay(Locale.CHINA));
							}
							dataarray.put(obj3);

						}

					}
				}

			}
			obj.put("datalist", dataarray);
		} catch (Exception e) {
			log.info("=======deletePartValidate======Exception" + e);
			code = errorcode;
			result = e.getMessage();
			log.error(e.getMessage(), e);
		} finally {
			try {
				obj.put("tmCode", code);
				obj.put("result", result);
				obj.put("datalist", dataarray);
				obj.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.info("=======deletePartValidate======Finally Exception" + e);
				log.error(e.getMessage(), e);
			}
		}
		return obj.toString();
	}

	/**
	 * 取父关系部件集合
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static List<WTPart> getParentParts(WTPart part, List<WTPart> list, String requestview) {
		QueryResult partsqr;
		try {
			// partsqr = PersistenceHelper.manager.navigate(part.getMaster(),
			// WTPartUsageLink.ALL_ROLES,WTPartUsageLink.class);

			List<WTPartUsageLink> linklist = getWTPartUsageLink(part);
			for (WTPartUsageLink link : linklist) {
				WTPart partA = (WTPart) link.getRoleAObject();
				if (!isNullOrEmpty(requestview) && !partA.getViewName().equals(requestview)) {
					continue;
				}
				/*
				 * log.info("=======partA:" + partA.getNumber() + "==" +
				 * partA.getViewName() + "====version:" +
				 * VersionControlHelper.getIterationDisplayIdentifier(partA).
				 * toString());
				 */
				List<WTPart> latestlist = getAllLatestVersionPart(partA.getNumber());
				if (latestlist.contains(partA) && !list.contains(partA) && partA.isLatestIteration()) {
					String softType = GenericUtil.getTypeId(partA);
					// if (softType.indexOf("cn.tianma.FinishedGood") != -1
					// || softType.indexOf("cn.tianma.SemiFinishedGood") != -1)
					// {
					String partstate = partA.getState().getState().getDisplay(Locale.CHINA);
					if ("正在工作".equals(partstate) || "新品".equals(partstate) || "试产".equals(partstate)
							|| "风险批量".equals(partstate) || "小批量".equals(partstate) || "量产发布".equals(partstate)) {
						// 第一层
						list.add(partA);
					}
					// }

					// 递归查询
					// getParentParts(partA, list);
				}

			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return list;
	}

	/**
	 * 替换物料校验
	 */
	public static String replacePartBomValidate(JSONArray array) {
		String result = "";
		JSONObject obj = new JSONObject();
		JSONArray dataarray = new JSONArray();
		List<String> errornumber = new ArrayList<String>();
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				BOMBean bean = new BOMBean();
				// 原料号
				String oldpartNumber = job.getString("oldnumber");
				// 原料号用量
				String oldamount = job.getString("oldamount");
				// 原料号行号
				String oldlinenumber = job.getString("oldlinenumber");
				// 新料号
				String newpartNumber = job.getString("newnumber");
				// 新料号用量
				String newpartamount = job.getString("newamount");
				// 新料号行号
				String newpartlinenumber = job.getString("newlinenumber");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// 视图
				String view = job.getString("view");
				// ECO oid
				String oid = job.getString("ecoid");

				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}

				bean.setEcoid(oid);
				bean.setOldpartnumber(oldpartNumber);
				bean.setOldpartamount(oldamount);
				bean.setOldpartlinenumber(oldlinenumber);
				bean.setNewpartnumber(newpartNumber);
				bean.setNewpartamount(newpartamount);
				bean.setNewpartlinenumber(newpartlinenumber);
				bean.setEffectnumber(effectNumber);
				bean.setView(view);
				bean.setIndex(rowNmuber);
				// 校验
				result += validatePartNumber(bean, errornumber, dataarray);
			}
		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		} finally {
			try {
				obj.put("tmCode", correctcode);
				obj.put("result", result);
				obj.put("datalist", dataarray);
				obj.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}

		}
		return obj.toString();
	}

	/**
	 * 
	 * @param bean
	 * @return
	 */
	public static String validatePartNumber(BOMBean bean, List<String> errornumber, JSONArray dataarray) {
		String result = "";
		JSONObject obj = new JSONObject();
		try {
			String bomnumber = bean.getEffectnumber();
			List<WTPart> list = BOMHelp.getAllLatestVersionPart(bomnumber);
			if (list.size() == 0) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
						+ effectpartname + bomnumber + "不存在;\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			}
			WTPart bompart = null;
			bompart = GenericUtil.getPart(bomnumber, "", bean.getView());
			WTPart part = PartUtil.getWTPartByNumber(bean.getOldpartnumber());

			if (part == null) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行" + oldpartname
						+ bean.getOldpartnumber() + "不存在;\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			} else {
				part = GenericUtil.getPart(bean.getOldpartnumber(), "", bean.getView());
				if (part == null) {
					result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
							+ oldpartname + bean.getOldpartnumber() + "不存在" + bean.getView() + "视图;\r";
					if (!errornumber.contains(bean.getIndex())) {
						errornumber.add(bean.getIndex());
					}
				}
			}
			WTPart newpart = PartUtil.getWTPartByNumber(bean.getNewpartnumber());

			if (newpart == null) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行" + newpartname
						+ bean.getNewpartnumber() + "不存在;\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			} else {
				newpart = GenericUtil.getPart(bean.getNewpartnumber(), "", bean.getView());
				if (newpart == null) {
					result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
							+ newpartname + bean.getNewpartnumber() + "不存在" + bean.getView() + "视图;\r";
					if (!errornumber.contains(bean.getIndex())) {
						errornumber.add(bean.getIndex());
					}
				} else {
					String state = newpart.getState().getState().getDisplay(Locale.CHINA);
					if ("废弃".equals(state)) {
						result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
								+ newpartname + bean.getNewpartnumber() + "状态为废弃，不能作为主料";
						if (!errornumber.contains(bean.getIndex())) {
							errornumber.add(bean.getIndex());
						}
					}
					if (bean.getNewpartnumber() != null && bomnumber != null
							&& bomnumber.equals(bean.getNewpartnumber())) {
						result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
								+ newpartname + bean.getNewpartnumber() + "与受影响对象编号相同";
						if (!errornumber.contains(bean.getIndex())) {
							errornumber.add(bean.getIndex());
						}
					}
				}
			}
			// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
			boolean flag = false;
			WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(bean.getEcoid()).getObject();
			// ......................
			List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(bomnumber, eco.getNumber());
			if (ecolist.size() != 0) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
						+ effectpartname + bomnumber + "已存在于未关闭的ECO变更流程中(" + ecolist.toString() + ")\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			}
			WTPartMaster childmaster = MyPartUtil.getWTPartMasterByNumber(bean.getOldpartnumber());

			QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
			List<String> partlist = new ArrayList<String>();
			Map<String, WTPartUsageLink> map = new HashMap<String, WTPartUsageLink>();
			Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
			while (groupqrq.hasMoreElements()) {
				WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
				// HashMap hm = new HashMap<String, String>();
				String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
				String linenumber = puse.getLineNumber().toString();
				// 用于校验
				partlist.add(number);
				// map.put(number, puse);
				// 用于返回显示的数据 存在多条子件编号相同的情况
				if (number.equals(bean.getOldpartnumber())) {
					linklist2.put(linenumber, puse);
				}
			}
			if (partlist.contains(bean.getNewpartnumber()) && !"H10".equals(bean.getView())) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行" + newpartname
						+ bean.getNewpartnumber() + "已存在于" + effectpartname + bomnumber + ";\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			}
			if (!partlist.contains(bean.getOldpartnumber())) {
				result += "第" + (StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex()) + "行"
						+ effectpartname + bomnumber + "中不存在" + oldpartname + bean.getOldpartnumber() + ";\r";
				if (!errornumber.contains(bean.getIndex())) {
					errornumber.add(bean.getIndex());
				}
			} else {
				/*
				 * JSONObject singleobj = new JSONObject();
				 * singleobj.put("oldnumber", bean.getOldpartnumber());
				 * singleobj.put("effectnumber", bean.getEffectnumber());
				 * singleobj.put("newnumber", bean.getNewpartnumber());
				 * singleobj.put("view", bean.getView());
				 * singleobj.put("oldamount",
				 * map.get(bean.getOldpartnumber()).getQuantity().getAmount());
				 * singleobj.put("oldlinenumber",
				 * map.get(bean.getOldpartnumber()).getLineNumber().toString());
				 * // 新用量采用旧用量 singleobj.put("newamount",
				 * map.get(bean.getOldpartnumber()).getQuantity().getAmount());
				 * // 新行号采用旧行号 singleobj.put("newlinenumber",
				 * map.get(bean.getOldpartnumber()).getLineNumber().toString());
				 * dataarray.put(singleobj);
				 */

				Iterator iter = linklist2.keySet().iterator();
				while (iter.hasNext()) {
					String linenumber = iter.next().toString();
					WTPartUsageLink link2 = linklist2.get(linenumber);

					JSONObject obj22 = new JSONObject();
					obj22.put("rowNmuber", StringUtil.isNullOrEmpty(bean.getIndex()) ? "" : bean.getIndex());
					obj22.put("oldnumber", bean.getOldpartnumber());
					obj22.put("effectnumber", bean.getEffectnumber());
					if (bompart != null) {
						obj22.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
						obj22.put("effectunit", bompart.getDefaultUnit());
					}
					obj22.put("newnumber", bean.getNewpartnumber());
					obj22.put("view", bean.getView());
					obj22.put("oldamount", link2.getQuantity().getAmount());
					obj22.put("oldlinenumber", linenumber);

					if (part != null) {
						obj22.put("oldstate", part.getState().getState().getDisplay(Locale.CHINA));
						obj22.put("oldunit", part.getDefaultUnit());
					}

					// 新用量采用旧用量
					obj22.put("newamount", link2.getQuantity().getAmount());
					// 新行号采用旧行号
					obj22.put("newlinenumber", linenumber);
					if (newpart != null) {
						obj22.put("newstate", newpart.getState().getState().getDisplay(Locale.CHINA));
						obj22.put("newunit", newpart.getDefaultUnit());
					}

					obj22.put("view", bean.getView());
					dataarray.put(obj22);

				}

			}

		} catch (Exception e) {
			result = e.getMessage();
		} /*
			 * finally { try { obj.put("tmCode", correctcode); obj.put("result",
			 * result); obj.put("datalist", dataarray); obj.put("errornumber",
			 * errornumber); } catch (JSONException e) {
			 * log.error(e.getMessage(), e); }
			 * 
			 * }
			 */
		return result;
	}

	/**
	 * 用量修改校验
	 */
	public static String updatePartAmountValidate(JSONArray array) {
		String result = "";
		JSONObject obj = null;
		JSONArray dataarray = null;
		List<String> errornumber = new ArrayList<String>();
		try {
			obj = new JSONObject();
			dataarray = new JSONArray();
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				// 原料号
				String oldpartNumber = job.getString("oldnumber");
				// 变更前用量
				String oldamount = job.getString("oldamount");
				// 行号
				String oldlinenumber = job.getString("oldlinenumber");
				// 变更后用量
				String newpartamount = job.getString("newamount");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// 视图
				String view = job.getString("view");

				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}

				// log.info("==========newpartamount:" + newpartamount);
				// log.info("==========effectNumber:" + effectNumber);
				// ECO oid
				String oid = job.getString("ecoid");
				// validateUpdateAmount(bean);
				WTPart bompart = GenericUtil.getPart(effectNumber, "", view);
				String ver = VersionControlHelper.getIterationDisplayIdentifier(bompart).toString();
				// log.info("==========ver:" + ver);
				if (bompart == null) {
					result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				/*
				 * for (WTPart part1 : list) { if
				 * (part1.getViewName().equals(bean.getView())) { bompart =
				 * part1; } }
				 */
				WTPart part = GenericUtil.getPart(oldpartNumber, "", view);
				if (part == null) {
					result += "第" + rowNmuber + "行" + changepartname + oldpartNumber + "不存在" + view + "视图;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
				boolean flag = false;
				WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();

				List<String> list22 = ECOCRUDUtil.queryHistoryByNumber(effectNumber, eco.getNumber());
				if (list22.size() != 0) {
					result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "已存在于未关闭的ECO变更流程中("
							+ list22.toString() + ")\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}

				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
				log.info("=============== 关系数量：" + groupqrq.size());
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();

				Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					String linenumber = puse.getLineNumber().toString();
					// log.info("====number===" + number);
					linklist.put(number, puse);
					if (number.equals(oldpartNumber)) {
						linklist2.put(linenumber, puse);
					}
				}
				// 若存在对应关系则返回前台相关属性
				if (linklist.containsKey(oldpartNumber)) {
					/*
					 * WTPartUsageLink link = linklist.get(oldpartNumber);
					 * JSONObject objlink = new JSONObject();
					 * objlink.put("oldnumber", oldpartNumber);
					 * objlink.put("oldamount", link.getQuantity().getAmount());
					 * if (link.getLineNumber() != null) {
					 * objlink.put("oldlinenumber",
					 * link.getLineNumber().toString()); } else {
					 * objlink.put("oldlinenumber", ""); }
					 * 
					 * objlink.put("newamount", isNullOrEmpty(newpartamount) ?
					 * "" : newpartamount); objlink.put("effectnumber",
					 * isNullOrEmpty(effectNumber) ? "" : effectNumber);
					 * dataarray.put(objlink);
					 */
					Iterator iter = linklist2.keySet().iterator();
					while (iter.hasNext()) {
						String linenumber = iter.next().toString();
						WTPartUsageLink link2 = linklist2.get(linenumber);

						JSONObject objlink = new JSONObject();
						objlink.put("oldnumber", oldpartNumber);
						objlink.put("oldamount", link2.getQuantity().getAmount());
						objlink.put("oldlinenumber", linenumber);
						if (part != null) {
							objlink.put("oldstate", part.getState().getState().getDisplay(Locale.CHINA));
						}
						objlink.put("oldunit", link2.getQuantity().getUnit());
						objlink.put("newamount", isNullOrEmpty(newpartamount) ? "" : newpartamount);

						objlink.put("effectnumber", isNullOrEmpty(effectNumber) ? "" : effectNumber);
						if (bompart != null) {
							objlink.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
							objlink.put("effectunit", bompart.getDefaultUnit());
						}

						objlink.put("rowNmuber", rowNmuber);
						objlink.put("view", view);
						dataarray.put(objlink);
					}

				} else {
					result += "第" + rowNmuber + "行" + changepartname + oldpartNumber + "不存在于" + effectpartname
							+ effectNumber + ";\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
			}
			// obj.put("datalist", dataarray);
		} catch (Exception e) {
			log.info("========Exception :" + e.getMessage());
			result += e.getMessage();
			log.error(e.getMessage(), e);
		} finally {
			try {
				obj.put("tmCode", correctcode);
				obj.put("result", result);
				log.info("========dataarray 2:" + dataarray.toString());
				obj.put("datalist", dataarray);
				obj.put("errornumber", errornumber);
			} catch (Exception e3) {
				log.info("========Exception 2:" + e3.getMessage());
				log.error(e3.getMessage(), e3);
			}
		}
		log.info("==========return:" + obj.toString());
		return obj.toString();
	}

	/**
	 * 查询BOM中批准的零件
	 * 返回格式：{status:success/failed,datalist:[{number:XX01,partRecognize
	 * :"是",whetherPartRecognize
	 * :"是"},{number:XX02,partRecognize:"是",whetherPartRecognize:"是"}]}
	 * partRecognize：是否需要零件承认，whetherPartRecognize：是否已经样品承认
	 * 
	 * @return
	 */
	public static String searhPart(String number, String view) {
		JSONObject obj = new JSONObject();
		JSONArray array = new JSONArray();
		List<WTPart> list = getAllLatestVersionPart(number);
		// 找指定视图的BOM
		WTPart bompart = null;
		List<WTPart> childlist = new ArrayList<WTPart>();
		log.info("===========view:" + view);
		if (!isNullOrEmpty(view)) {
			log.info("===========view not null ==========");
			/*
			 * for (WTPart part1 : list) { if (part1.getViewName().equals(view))
			 * { bompart = part1; } }
			 */
			try {
				bompart = GenericUtil.getPart(number, "", view);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			// 找BOM下的零件
			// Vector<WTPart> vect = new Vector<WTPart>();
			try {
				if (bompart != null) {
					// vect = PartUtil.getSubPartListByPart(bompart, view);
					childlist = getchildPart(bompart, childlist);
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
			log.info("===========view  childlist 1==========" + childlist.size());
		} else {
			log.info("===========view  null ==========");
			for (WTPart part1 : list) {
				// vect = PartUtil.getSubPartListByPart(bompart, view);
				childlist = getchildPart(part1, childlist);
			}
			log.info("===========view  childlist 2 ==========" + childlist.size());
		}

		try {
			obj.put("status", TMECOUtil.correctStatus);
			log.info("SBOM================childlist:" + childlist.size());
			// 返回零件的信息
			for (WTPart part : childlist) {
				JSONObject object = new JSONObject();
				try {
					String partRecognize = "";
					String whetherPartRecognize = "";
					whetherPartRecognize = (String) LWCUtil.getValue(part, "whetherPartRecognize");
					partRecognize = (String) LWCUtil.getValue(part, "partRecognize");
					if (!isNullOrEmpty(partRecognize) && "是".equals(partRecognize)) {
						// 零件号
						object.put("number", part.getNumber());
						object.put("name", part.getName());
						// 是否需要零件承认
						object.put("partRecognize", partRecognize);
						// 是否已经样品承认
						object.put("whetherPartRecognize", whetherPartRecognize);
						// 视图 view
						object.put("view", part.getViewName());
						// 修改者 updateBy
						object.put("updateBy", CommonPDMUtil.getModifierName(part));
						array.put(object);
					}
				} catch (WTException e) {

					// object.put("partRecognize", "");
				}
			}
			obj.put("datalist", array);

		} catch (JSONException e) {
			log.error(e.getMessage(), e);
		}
		return obj.toString();
	}

	/**
	 * 检验替换物料
	 */
	public static String replacePartBomCheck(JSONArray array) {
		String result = "";
		JSONObject object = new JSONObject();
		JSONArray dataarray = new JSONArray();
		for (int i = 0; i < array.length(); i++) {
			try {
				Object obj = array.get(i);
				if (obj != null) {
					JSONObject job = (JSONObject) obj;
					BOMBean bean = new BOMBean();
					// 原料号
					String oldpartNumber = job.getString("oldnumber");
					// 原料号用量
					String oldamount = job.getString("oldamount");
					// 原料号行号
					String oldlinenumber = job.getString("oldlinenumber");
					// 新料号
					String newpartNumber = job.getString("newnumber");
					// 新料号用量
					String newpartamount = job.getString("newamount");
					// 新料号行号
					String newpartlinenumber = job.getString("newlinenumber");
					// 受影响对象编号
					String effectNumber = job.getString("effectnumber");
					// 视图
					String view = job.getString("view");

					bean.setOldpartnumber(oldpartNumber);
					bean.setOldpartamount(oldamount);
					bean.setOldpartlinenumber(oldlinenumber);
					bean.setNewpartnumber(newpartNumber);
					bean.setNewpartamount(newpartamount);
					bean.setNewpartlinenumber(newpartlinenumber);
					bean.setEffectnumber(effectNumber);
					bean.setView(view);

				}
			} catch (JSONException e) {
				result = "替换物料失败：" + e.getMessage();
				log.error(e.getMessage(), e);
			} finally {
				try {
					object.put("tmcode", BOMHelp.correctcode);
					object.put("result", result);
				} catch (JSONException e) {
					log.error(e.getMessage(), e);
				}
			}
		}

		return object.toString();
	}

	/**
	 * 查询ECO变更清单 参数key的值为：ECONumber、ECOPARTNUMBER、ECOView、ECOOperatingType、name
	 * 
	 * @param key
	 *            ECO编号、成品编号、变更类型、成品名称
	 * @param value
	 * @return
	 * 
	 * 		{status:"",datalist[{econumber:"",createtime:"",creator:"",},{},{
	 *         }]}
	 */
	public static String queryECOOrder(String key, String value, String startdate, String enddate) {
		String result = "";
		// 因ECO清单中 未存储名称 ，故搜索名称时，转化为编号去搜索
		/*
		 * WTPart part = null; if ("name".equals(key)) { try { part =
		 * getWTPartByName(value); } catch (WTException e) {
		 * e.printStackTrace(); } } if (part != null) { key = "ECOPARTNUMBER";
		 * value = part.getNumber(); }
		 */
		// ECO查询结果返回值
		result = ecoResult(key, value, startdate, enddate);

		return result;

	}

	/**
	 * 根据名称找Part
	 * 
	 * @param partname
	 * @return
	 * @throws WTException
	 */
	public static WTPart getWTPartByName(String partname) throws WTException {
		WTPart part = null;
		QuerySpec qs = null;
		QueryResult qr = null;
		qs = new QuerySpec(WTPartMaster.class);
		// 根据零件编号查询
		SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NAME, SearchCondition.EQUAL,
				partname);
		qs.appendSearchCondition(sc);
		qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			WTPartMaster master = (WTPartMaster) qr.nextElement();
			// 根据master得到最新版本的零件
			part = PartUtil.getLatestPartByPartMaster(master);
			break;
		}
		return part;
	}

	/**
	 * 查询ECO清单返回结果
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static String ecoResult(String key, String value, String startdate, String enddate) {
		URLFactory urlfactory;
		String baseHref = "";
		String url = "";
		try {
			urlfactory = new URLFactory();
			baseHref = urlfactory.getBaseHREF();
		} catch (WTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();
		String status = TMECOUtil.correctStatus;
		// 根据关键字搜索ECO变更清单
		List<ECOBean> beans = ECOCRUDUtil.queryECOOrder(key, value, startdate, enddate);
		for (ECOBean bean : beans) {
			JSONObject obj = new JSONObject();
			WTChangeOrder2 eco = null;
			try {
				String creator = "";
				if (!isNullOrEmpty(bean.getECONumber())) {
					try {
						eco = getWTChangeOrder2ByNumber(bean.getECONumber());
						creator = eco.getCreatorName();
						WTUser wtUser = getUserByName(creator);
						//全名称
						creator = wtUser.getFullName();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				// 根据创建者返回信息
				if ("creator".equals(key)) {
				//	if (value.equals(creator)) {
					//模糊搜索
					if (creator.indexOf(value)!=-1) {
						String ufid;
						try {
							ufid = GenericUtil.getOid(eco);
							url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						String href = "<a href='" + url + "' target='_blank' >" + bean.getECONumber() + "</a>";
						// obj.put("econumber", bean.getECONumber());
						System.out.println("=====href:" + href);
						obj.put("econumber", href);
						obj.put("url", url);
						/*
						 * obj.put("ecoeffectnumber",
						 * bean.getECOAffectnumber()); obj.put("ecoview",
						 * bean.getECOView()); obj.put("operatetype",
						 * bean.getECOOperatingType());
						 */
						obj.put("createtime", bean.getCreatetime());
						obj.put("creator", creator);
						array.put(obj);
					}
				} else {
					String ufid;
					try {
						ufid = GenericUtil.getOid(eco);
						url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					String href = "<a href='" + url + "' target='_blank' >" + bean.getECONumber() + "</a>";
					// obj.put("econumber", bean.getECONumber());
					System.out.println("=====href:" + href);
					obj.put("econumber", href);
					obj.put("url", url);
					// obj.put("econumber", bean.getECONumber());
					/*
					 * obj.put("ecoeffectnumber", bean.getECOAffectnumber());
					 * obj.put("ecoview", bean.getECOView());
					 * obj.put("operatetype", bean.getECOOperatingType());
					 */
					obj.put("createtime", bean.getCreatetime());
					obj.put("creator", creator);
					array.put(obj);
				}
			} catch (JSONException e) {
				status = TMECOUtil.errorStatus;
				e.printStackTrace();
			}
		}
		try {
			object.put("status", status);
			object.put("datalist", array);
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {

		}
		return object.toString();
	}

	/**
	 * 新增替代料校验
	 */
	public static String addReplacePartBOMValidate(JSONArray array) {
		String result = "";
		JSONObject object = new JSONObject();
		JSONArray arraylist = new JSONArray();
		List<String> errornumber = new ArrayList<String>();
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				// 主料号
				String partANumber = job.getString("numberA");
				// 主料行号
				String partAlinenumber = job.getString("linenumberA");
				// 替代料号
				String partBNumber = job.getString("numberB");
				// 替代料用量
				String AmountB = job.getString("amountB");
				// 替代料行号
				String linenumberB = job.getString("linenumberB");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// ECO oid
				String oid = job.getString("ecoid");
				// view
				String view = job.getString("view");

				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}
				// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
				boolean flag = false;
				WTChangeOrder2 eco;
				eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
				//
				// 取关系先判断是否已经存在关系
				PartUtil.getWTPartByNumber(partBNumber);
				WTPart bompart = PartUtil.getWTPartByNumber(effectNumber);
				if (bompart == null) {
					result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					bompart = GenericUtil.getPart(effectNumber, "", view);
					if (bompart == null) {
						result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				}
				WTPart partA = PartUtil.getWTPartByNumber(partANumber);
				if (partA == null) {
					result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partA = GenericUtil.getPart(partANumber, "", view);
					if (partA == null) {
						result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				}
				WTPart partB = PartUtil.getWTPartByNumber(partBNumber);
				if (partB == null) {
					result += "第" + rowNmuber + "行" + newaddreplacepartname + partBNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partB = GenericUtil.getPart(partBNumber, "", view);
					if (partB == null) {
						result += "第" + rowNmuber + "行" + newaddreplacepartname + partBNumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} /*
						 * else { //去掉替代料废弃校验 String state =
						 * partB.getState().getState().getDisplay(Locale.CHINA);
						 * if ("废弃".equals(state)) { result += "第" + rowNmuber +
						 * "行" + newaddreplacepartname + partBNumber + "状态为废弃;";
						 * if (!errornumber.contains(rowNmuber)) {
						 * errornumber.add(rowNmuber); } } }
						 */

				}
				List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(effectNumber, eco.getNumber());
				if (ecolist.size() != 0) {
					result += "第" + rowNmuber + "行" + effectpartname + partBNumber + "已存在于未关闭的ECO变更流程中("
							+ ecolist.toString() + ")\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				WTPartMaster childAmaster = MyPartUtil.getWTPartMasterByNumber(partANumber);

				WTPartMaster childBmaster = MyPartUtil.getWTPartMasterByNumber(partBNumber);
				if (partB != null) {
					childBmaster = (WTPartMaster) (partB.getMaster());
				}

				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();

				Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					HashMap hm = new HashMap<String, String>();
					// A 父节点 B 子节点 ((WTPartMaster)
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					String linenumber = puse.getLineNumber().toString();
					linklist.put(number, puse);
					if (number.equals(partANumber)) {
						linklist2.put(linenumber, puse);
					}
				}

				// 受影响对象BOM下包含主料时 创建主料与替换料的关系
				if (linklist.containsKey(partANumber)) {
					/*
					 * WTPartUsageLink oldlink = linklist.get(partANumber);
					 * WTCollection wtcol =
					 * WTPartHelper.service.getSubstituteLinks(oldlink);
					 * 
					 * WTPartSubstituteLink sublink =
					 * SubstituteLinkUtil.getSubstituteLink(childBmaster,
					 * wtcol); log.info("=========删除替代料关系 1 ==========" +
					 * sublink); if (sublink != null) { result +=
					 * newaddreplacepartname + partBNumber + "替换关系已存在;\r"; }
					 * 
					 * JSONObject obj2 = new JSONObject(); // 主料号
					 * obj2.put("numberA", partANumber); obj2.put("linenumberA",
					 * oldlink.getLineNumber().toString()); obj2.put("numberB",
					 * partBNumber); obj2.put("amountB", AmountB);
					 * obj2.put("linenumberB", linenumberB);
					 * obj2.put("effectnumber", effectNumber);
					 * arraylist.put(obj2);
					 */

					Iterator iter = linklist2.keySet().iterator();
					while (iter.hasNext()) {
						String linenumber = iter.next().toString();
						WTPartUsageLink link2 = linklist2.get(linenumber);

						WTCollection wtcol2 = WTPartHelper.service.getSubstituteLinks(link2);

						WTPartSubstituteLink sublink2 = SubstituteLinkUtil.getSubstituteLink(childBmaster, wtcol2);
						log.info("=========删除替代料关系 1 ==========" + sublink2);
						if (sublink2 != null) {
							result += "第" + rowNmuber + "行" + newaddreplacepartname + partBNumber + "替换关系已存在;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}

						JSONObject obj3 = new JSONObject();
						// 主料号
						obj3.put("numberA", partANumber);
						obj3.put("linenumberA", linenumber);
						if (partA != null) {
							obj3.put("unitA", partA.getDefaultUnit());
							obj3.put("stateA", partA.getState().getState().getDisplay(Locale.CHINA));
						}

						obj3.put("numberB", partBNumber);
						obj3.put("amountB", link2.getQuantity().getAmount());
						obj3.put("linenumberB", linenumberB);
						if (partB != null) {
							obj3.put("unitB", partB.getDefaultUnit());
							obj3.put("stateB", partB.getState().getState().getDisplay(Locale.CHINA));
						}
						obj3.put("effectnumber", effectNumber);
						obj3.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
						obj3.put("view", view);

						obj3.put("rowNmuber", rowNmuber);

						arraylist.put(obj3);

					}

				} else {
					result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在于" + effectpartname
							+ effectNumber + ";\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}

			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result += e.getMessage();
			System.out.println("===========Exception:" + e.getMessage());
		} finally {
			try {
				object.put("tmcode", BOMHelp.correctcode);
				object.put("result", result);
				object.put("datalist", arraylist);
				object.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}
		}
		return object.toString();
	}

	/**
	 * 删除替换料 校验
	 */
	public static String deleteReplacePartBOMValidate(JSONArray array) {
		String result = "";
		List<String> errornumber = new ArrayList<String>();
		JSONObject object = new JSONObject();
		JSONArray arraylist = new JSONArray();
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				// BOMBean bean = new BOMBean();
				// 主料号
				String partANumber = job.getString("numberA");
				// 主料行号
				String partAlinenumber = job.getString("linenumberA");
				// 替代料号
				String partBNumber = job.getString("numberB");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// ECO oid
				String oid = job.getString("ecoid");
				// view
				String view = job.getString("view");
				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}
				/*
				 * bean.setEcoid(oid); bean.setView(view);
				 * bean.setType(BOMBean.DelReplcePart);
				 * bean.setPartAnumber(partANumber);
				 * bean.setPartAlinenumber(partAlinenumber);
				 * bean.setPartBnumber(partBNumber);
				 * bean.setEffectnumber(effectNumber);
				 */

				// 取关系先判断是否已经存在关系
				try {
					WTPart bompart = GenericUtil.getPart(effectNumber, "", view);

					WTPartMaster partBMaster = MyPartUtil.getWTPartMasterByNumber(partBNumber);
					if (bompart == null) {
						result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					WTPart partA = PartUtil.getWTPartByNumber(partANumber);
					if (partA == null) {
						result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						partA = GenericUtil.getPart(partANumber, "", view);
						if (partA == null) {
							result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在" + view + "视图;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
					}
					WTPart partB = PartUtil.getWTPartByNumber(partBNumber);
					if (partB == null) {
						result += "第" + rowNmuber + "行" + delreplacepartname + partBNumber + "不存在;\r";
					} else {
						partB = GenericUtil.getPart(partBNumber, "", view);
						if (partB == null) {
							result += "第" + rowNmuber + "行" + delreplacepartname + partBNumber + "不存在" + view + "视图;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
					}
					// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
					boolean flag = false;
					WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
					// ......................
					List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(effectNumber, eco.getNumber());
					if (ecolist.size() != 0) {
						result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "已存在于未关闭的ECO变更流程中("
								+ ecolist.toString() + ")\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
					Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
					Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
					while (groupqrq.hasMoreElements()) {
						WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
						String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
						String linenumber = puse.getLineNumber().toString();
						linklist.put(number, puse);
						if (number.equals(partANumber)) {
							linklist2.put(linenumber, puse);
						}
					}

					// 确认受影响对象BOM结构下包含主料A
					if (linklist.containsKey(partANumber)) {

						/*
						 * WTPartUsageLink oldlink = linklist.get(partANumber);
						 * WTCollection wtcol =
						 * WTPartHelper.service.getSubstituteLinks(oldlink);
						 * 
						 * WTPartSubstituteLink sublink =
						 * SubstituteLinkUtil.getSubstituteLink(partBMaster,
						 * wtcol); log.info("=========删除替代料关系 1 ==========" +
						 * sublink); if (sublink == null) { result +=
						 * delreplacepartname + partBNumber + "与" + mainpartname
						 * + partANumber + "不存在替换关系;\r"; }
						 * 
						 * JSONObject obj2 = new JSONObject();
						 * obj2.put("effectnumber", effectNumber);
						 * obj2.put("numberB", partBNumber); obj2.put("numberA",
						 * partANumber); if
						 * (linklist.get(partANumber).getLineNumber() != null) {
						 * obj2.put("linenumberA",
						 * linklist.get(partANumber).getLineNumber().toString())
						 * ; } else { obj2.put("linenumberA", ""); }
						 * 
						 * arraylist.put(obj2);
						 */

						Iterator iter = linklist2.keySet().iterator();
						while (iter.hasNext()) {
							String linenumber = iter.next().toString();
							WTPartUsageLink link2 = linklist2.get(linenumber);

							WTCollection wtcol = WTPartHelper.service.getSubstituteLinks(link2);

							WTPartSubstituteLink sublink = SubstituteLinkUtil.getSubstituteLink(partBMaster, wtcol);
							log.info("=========删除替代料关系 1 ==========" + sublink);
							if (sublink == null) {
								result += "第" + rowNmuber + "行" + delreplacepartname + partBNumber + "与" + mainpartname
										+ partANumber + "不存在替换关系;\r";
								if (!errornumber.contains(rowNmuber)) {
									errornumber.add(rowNmuber);
								}
							}

							JSONObject obj2 = new JSONObject();
							obj2.put("rowNmuber", rowNmuber);
							obj2.put("effectnumber", effectNumber);
							obj2.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));

							obj2.put("numberB", partBNumber);
							if (partB != null) {
								obj2.put("unitB", partB.getDefaultUnit());
								obj2.put("stateB", partB.getState().getState().getDisplay(Locale.CHINA));
							}
							if (partA != null) {
								obj2.put("unitA", partA.getDefaultUnit());
								obj2.put("stateA", partA.getState().getState().getDisplay(Locale.CHINA));
							}

							obj2.put("numberA", partANumber);
							obj2.put("linenumberA", linenumber);
							obj2.put("view", view);
							arraylist.put(obj2);

						}

					} else {
						result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在于" + effectpartname
								+ effectNumber + ";\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}

			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result = e.getMessage();
		} finally {
			try {
				object.put("tmcode", BOMHelp.correctcode);
				object.put("result", result);
				object.put("datalist", arraylist);
				object.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}
		}
		return object.toString();
	}

	/**
	 * 更换主料 校验
	 * 
	 */
	public static String repalcePartAValidate(JSONArray array) {
		JSONObject object = new JSONObject();
		JSONArray arrays = new JSONArray();
		List<String> errornumber = new ArrayList<String>();
		String result = "";
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				// BOMBean bean = new BOMBean();
				// 原主料料号
				String oldpartNumber = job.getString("oldpartnumber");
				// 原主料用量
				String oldpartamount = job.getString("oldpartamount");
				// 原主料行号
				String oldpartlinenumber = job.getString("oldpartlinenumber");
				// 新主料料料号
				String newpartNumber = job.getString("newpartnumber");
				// 新主料料用量
				String newpartAmount = job.getString("newpartamount");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// 视图
				String view = job.getString("view");
				// ECO oid
				String oid = job.getString("ecoid");

				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}
				/*
				 * bean.setEcoid(oid); bean.setType(BOMBean.UpdateAPart);
				 * bean.setOldpartnumber(oldpartNumber);
				 * bean.setOldpartamount(oldpartamount);
				 * bean.setOldpartlinenumber(oldpartlinenumber);
				 * bean.setNewpartnumber(newpartNumber);
				 * bean.setNewpartamount(newpartAmount); //
				 * bean.setNewpartlinenumber(newpartlinenumber);
				 * bean.setEffectnumber(effectNumber); bean.setView(view);
				 */
				// 先判断是否已经存在关系
				try {
					List<WTPart> list = BOMHelp.getAllLatestVersionPart(effectNumber);
					if (list.size() == 0) {
						result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					WTPart bompart = GenericUtil.getPart(effectNumber, "", view);
					WTPart part = PartUtil.getWTPartByNumber(oldpartNumber);
					if (part == null) {
						result += "第" + rowNmuber + "行" + oldmainpartname + oldpartNumber + "不存在;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						part = GenericUtil.getPart(oldpartNumber, "", view);
						if (part == null) {
							result += "第" + rowNmuber + "行" + oldmainpartname + oldpartNumber + "不存在" + view + "视图;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
					}
					WTPart newpart = PartUtil.getWTPartByNumber(newpartNumber);
					if (newpart == null) {
						result += "第" + rowNmuber + "行" + newmainpartname + newpartNumber + "不存在;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						newpart = GenericUtil.getPart(newpartNumber, "", view);
						if (newpart == null) {
							result += "第" + rowNmuber + "行" + newmainpartname + newpartNumber + "不存在" + view + "视图;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						} else {
							String state = newpart.getState().getState().getDisplay(Locale.CHINA);
							if ("废弃".equals(state)) {
								result += "第" + rowNmuber + "行" + newmainpartname + newpartNumber + "状态为废弃，不能作为主料";
								if (!errornumber.contains(rowNmuber)) {
									errornumber.add(rowNmuber);
								}
							}
							if (newpartNumber.equals(effectNumber)) {
								result += "第" + rowNmuber + "行" + newmainpartname + newpartNumber + "与受影响对象编号"
										+ effectNumber + "相同";
								if (!errornumber.contains(rowNmuber)) {
									errornumber.add(rowNmuber);
								}
							}
						}
					}
					// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
					boolean flag = false;
					WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
					// ......................
					List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(newpartNumber, eco.getNumber());
					if (ecolist.size() != 0) {
						result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "已存在于未关闭的ECO变更流程中("
								+ ecolist.toString() + ")\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
					QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
					// 编号 -- 关系
					Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
					// 行号 -- 关系
					Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();

					while (groupqrq.hasMoreElements()) {
						WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
						String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
						String linenumber = puse.getLineNumber() == null ? "" : puse.getLineNumber().toString();
						linklist.put(number, puse);
						if (number.equals(oldpartNumber)) {
							linklist2.put(linenumber, puse);
						}
					}
					if (linklist.containsKey(newpartNumber)) {
						result += "第" + rowNmuber + "行" + newmainpartname + newpartNumber + "存在于" + effectpartname
								+ effectNumber + "中;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}

					if (!linklist.containsKey(oldpartNumber)) {
						result += "第" + rowNmuber + "行" + oldmainpartname + oldpartNumber + "不存在于" + effectpartname
								+ effectNumber + "中;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						/*
						 * JSONObject obj2 = new JSONObject(); WTPartUsageLink
						 * oldlink = linklist.get(oldpartNumber);
						 * obj2.put("effectnumber", effectNumber);
						 * obj2.put("view", view); obj2.put("oldpartnumber",
						 * oldpartNumber); obj2.put("oldpartamount",
						 * oldlink.getQuantity().getAmount());
						 * obj2.put("oldpartlinenumber",
						 * oldlink.getLineNumber().toString());
						 * obj2.put("newpartnumber", newpartNumber);
						 * obj2.put("newpartamount", newpartAmount);
						 * arrays.put(obj2);
						 */

						Iterator iter = linklist2.keySet().iterator();
						while (iter.hasNext()) {
							String linenumber = iter.next().toString();
							WTPartUsageLink link2 = linklist2.get(linenumber);

							JSONObject obj2 = new JSONObject();
							obj2.put("effectnumber", effectNumber);
							obj2.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
							obj2.put("view", view);
							obj2.put("oldpartnumber", oldpartNumber);
							obj2.put("oldpartamount", link2.getQuantity().getAmount());
							if (part != null) {
								obj2.put("oldstate", part.getState().getState().getDisplay(Locale.CHINA));
								obj2.put("oldunit", part.getDefaultUnit());
							}

							obj2.put("oldpartlinenumber", linenumber);
							obj2.put("newpartnumber", newpartNumber);
							obj2.put("newpartamount", newpartAmount);
							if (newpart != null) {
								obj2.put("newstate", newpart.getState().getState().getDisplay(Locale.CHINA));
								obj2.put("newunit", newpart.getDefaultUnit());
							}

							obj2.put("rowNmuber", rowNmuber);
							arrays.put(obj2);

						}

					}
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result = e.getMessage();
		} finally {
			try {
				object.put("tmcode", BOMHelp.correctcode);
				object.put("result", result);
				object.put("datalist", arrays);
				object.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}
		}
		return object.toString();
	}

	/**
	 * 主次替换 校验
	 * 
	 */
	public static String repalcePartAAndPartBValidate(JSONArray array) {
		String result = "";
		JSONObject object = new JSONObject();
		JSONArray arrays = new JSONArray();
		List<String> errornumber = new ArrayList<String>();
		try {
			for (int i = 0; i < array.length(); i++) {
				JSONObject job = (JSONObject) array.get(i);
				BOMBean bean = new BOMBean();
				// 原主料料号
				String partANumber = job.getString("partANumber");
				// 原替代料号
				String partBNumber = job.getString("partBNumber");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// 视图
				String view = job.getString("view");
				// ECO oid
				String oid = job.getString("ecoid");
				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}

				bean.setEcoid(oid);
				bean.setView(view);
				bean.setOldpartnumber(partANumber);
				bean.setNewpartnumber(partBNumber);
				// bean.setNewpartlinenumber(newpartlinenumber);
				bean.setEffectnumber(effectNumber);
				bean.setType(BOMBean.ReplaceABPart);

				String bomnumber = bean.getEffectnumber();
				List<WTPart> list = BOMHelp.getAllLatestVersionPart(bomnumber);
				if (list.size() == 0) {
					result += "第" + rowNmuber + "行" + effectpartname + bomnumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				// 先校验物料是否存在，再校验是否存在相应的关系
				WTPart bompart = GenericUtil.getPart(effectNumber, "", view);
				WTPart partA = PartUtil.getWTPartByNumber(partANumber);
				if (partA == null) {
					result += "第" + rowNmuber + "行" + oldmainpartname + partANumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partA = GenericUtil.getPart(partANumber, "", view);
					if (partA == null) {
						result += "第" + rowNmuber + "行" + oldmainpartname + partANumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				}
				WTPart partB = PartUtil.getWTPartByNumber(partBNumber);
				WTPartMaster partAMaster = MyPartUtil.getWTPartMasterByNumber(partANumber);
				WTPartMaster partBMaster = MyPartUtil.getWTPartMasterByNumber(partBNumber);
				if (partB == null) {
					result += "第" + rowNmuber + "行" + oldreplacepartname + partBNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partB = GenericUtil.getPart(partBNumber, "", view);
					if (partB == null) {
						result += "第" + rowNmuber + "行" + oldreplacepartname + partBNumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} else {
						String state = partB.getState().getState().getDisplay(Locale.CHINA);
						if ("废弃".equals(state)) {
							result += "第" + rowNmuber + "行" + oldreplacepartname + partBNumber + "状态为废弃，不能作为主料";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}
					}
				}
				// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
				boolean flag = false;
				WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
				// ......................
				List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(partBNumber, eco.getNumber());
				if (ecolist.size() != 0) {
					result += "第" + rowNmuber + "行" + oldreplacepartname + partBNumber + "已存在于未关闭的ECO变更流程中("
							+ ecolist.toString() + ")\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
				// 编号 link
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
				// 行号 link
				Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					String linenumber = puse.getLineNumber().toString();
					linklist.put(number, puse);
					if (number.equals(partANumber)) {
						linklist2.put(linenumber, puse);
					}
				}
				if (linklist.containsKey(partANumber)) {
					/*
					 * WTPartUsageLink puse = linklist.get(partANumber);
					 * 
					 * String linenumber = ""; if
					 * (!StringUtil.isNullOrEmpty(puse.getLineNumber().toString(
					 * ))) { linenumber = puse.getLineNumber().toString(); }
					 * 
					 * //
					 * SubstituteLinkUtil.getWTPartUsageLink(bompart,partAMaster
					 * ); WTCollection wtcol =
					 * WTPartHelper.service.getSubstituteLinks(puse);
					 * 
					 * WTPartSubstituteLink sublink =
					 * SubstituteLinkUtil.getSubstituteLink(partBMaster, wtcol);
					 * log.info("========主次替换中的  替代料关系 1 ==========" + sublink);
					 * if (sublink == null) { result += oldreplacepartname +
					 * partBNumber + "替换关系不存在;\r"; }
					 * 
					 * JSONObject obj2 = new JSONObject();
					 * obj2.put("partANumber", partANumber); //
					 * obj2.put("linenumber", linenumber);
					 * obj2.put("partBNumber", partBNumber);
					 * obj2.put("effectnumber", effectNumber); arrays.put(obj2);
					 */

					//
					Iterator iter = linklist2.keySet().iterator();
					while (iter.hasNext()) {
						String linenumber = iter.next().toString();
						WTPartUsageLink link2 = linklist2.get(linenumber);

						WTCollection wtcol = WTPartHelper.service.getSubstituteLinks(link2);

						WTPartSubstituteLink sublink = SubstituteLinkUtil.getSubstituteLink(partBMaster, wtcol);
						log.info("========主次替换中的  替代料关系 1 ==========" + sublink);
						if (sublink == null) {
							result += "第" + rowNmuber + "行" + oldreplacepartname + partBNumber + "替换关系不存在;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						}

						JSONObject obj2 = new JSONObject();
						obj2.put("partANumber", partANumber);
						if (partA != null) {
							obj2.put("unitA", partA.getDefaultUnit());
							obj2.put("stateA", partA.getState().getState().getDisplay(Locale.CHINA));
						}

						obj2.put("linenumber", linenumber);
						obj2.put("partBNumber", partBNumber);
						if (partB != null) {
							obj2.put("unitB", partB.getDefaultUnit());
							obj2.put("stateB", partB.getState().getState().getDisplay(Locale.CHINA));
						}
						obj2.put("effectnumber", effectNumber);
						obj2.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
						obj2.put("view", view);
						obj2.put("rowNmuber", rowNmuber);
						arrays.put(obj2);

					}
				} else {
					result += "第" + rowNmuber + "行" + oldmainpartname + partANumber + "不存在于" + effectpartname
							+ effectNumber + "中;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				/*
				 * if (linklist.containsKey(partBNumber)) { result +=
				 * effectpartname + effectNumber + "中已存在" + oldreplacepartname +
				 * partBNumber + ";\r"; }
				 */
				/*
				 * QueryResult groupqrqA = WTPartHelper.service
				 * .getUsesWTPartMasters(partA);
				 * 
				 * Map<String, WTPartUsageLink> listA = new HashMap<String,
				 * WTPartUsageLink>(); while (groupqrqA.hasMoreElements()) {
				 * WTPartUsageLink puse = (WTPartUsageLink) groupqrqA
				 * .nextElement(); String number = ((WTPartMaster)
				 * puse.getRoleBObject()) .getNumber(); listA.put(number, puse);
				 * } if (!listA.containsKey(partBNumber)) { result +=
				 * oldreplacepartname + partBNumber + "不存在于" + oldmainpartname +
				 * partANumber + "中;\r"; }
				 */
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result = e.getMessage();
		} finally {
			try {
				object.put("tmcode", BOMHelp.correctcode);
				object.put("result", result);
				object.put("datalist", arrays);
				object.put("errornumber", errornumber);
			} catch (JSONException e) {
				log.error(e.getMessage(), e);
			}
		}
		return object.toString();

	}

	/**
	 * 更换替代料 校验
	 */
	public static String replaceOldPartBomValidate(JSONArray array) {
		JSONObject object = new JSONObject();
		JSONArray arraylist = new JSONArray();
		List<String> errornumber = new ArrayList<String>();
		String result = "";
		for (int i = 0; i < array.length(); i++) {
			try {
				JSONObject job = (JSONObject) array.get(i);
				// BOMBean bean = new BOMBean();
				// 主料料号
				String partANumber = job.getString("partAnumber");
				// 行号
				String partAlinenumber = job.getString("partAlinenumber");
				// 原替换料料号
				String oldpartNumber = job.getString("oldpartnumber");
				// 原替换料用量
				String oldpartamount = job.getString("oldpartamount");
				// 新替换料料号
				String newpartNumber = job.getString("newpartnumber");
				// 新替换料用量
				String newpartAmount = job.getString("newpartamount");
				// 受影响对象编号
				String effectNumber = job.getString("effectnumber");
				// 视图
				String view = job.getString("view");
				// ECO oid
				String oid = job.getString("ecoid");
				String rowNmuber = "";
				if (job.has("rowNmuber")) {
					rowNmuber = job.getString("rowNmuber");
				}
				/*
				 * bean.setEcoid(oid); bean.setType(BOMBean.UpdateReplcePart);
				 * bean.setPartAnumber(partANumber);
				 * bean.setPartAlinenumber(partAlinenumber);
				 * bean.setOldpartnumber(oldpartNumber);
				 * bean.setOldpartamount(oldpartamount);
				 * bean.setNewpartnumber(newpartNumber);
				 * bean.setNewpartamount(newpartAmount); bean.setView(view);
				 */
				// bean.setNewpartlinenumber(newpartlinenumber);
				// bean.setEffectnumber(effectNumber);
				// 校验
				List<WTPart> list = BOMHelp.getAllLatestVersionPart(effectNumber);
				if (list.size() == 0) {
					result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				// 先校验物料是否存在，再校验是否存在相应的关系
				WTPart bompart = GenericUtil.getPart(effectNumber, "", view);
				WTPart partA = PartUtil.getWTPartByNumber(partANumber);
				if (partA == null) {
					result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partA = GenericUtil.getPart(partANumber, "", view);
					if (partA == null) {
						result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				}
				WTPart partB1 = PartUtil.getWTPartByNumber(oldpartNumber);
				if (partB1 == null) {
					result += "第" + rowNmuber + "行" + oldreplacepartname + oldpartNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partB1 = GenericUtil.getPart(oldpartNumber, "", view);
					if (partB1 == null) {
						result += "第" + rowNmuber + "行" + oldreplacepartname + oldpartNumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					}
				}
				WTPartMaster partB1Master = MyPartUtil.getWTPartMasterByNumber(oldpartNumber);
				WTPart partB2 = PartUtil.getWTPartByNumber(newpartNumber);
				if (partB2 == null) {
					result += "第" + rowNmuber + "行" + newreplacepartname + newpartNumber + "不存在;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				} else {
					partB2 = GenericUtil.getPart(newpartNumber, "", view);
					if (partB2 == null) {
						result += "第" + rowNmuber + "行" + newreplacepartname + newpartNumber + "不存在" + view + "视图;\r";
						if (!errornumber.contains(rowNmuber)) {
							errornumber.add(rowNmuber);
						}
					} /*
						 * else{ //去掉替代料废弃校验 String state =
						 * partB2.getState().getState().getDisplay(Locale.CHINA)
						 * ; if ("废弃".equals(state)) { result += "第" + rowNmuber
						 * + "行" + newreplacepartname + newpartNumber +
						 * "状态为废弃;"; if (!errornumber.contains(rowNmuber)) {
						 * errornumber.add(rowNmuber); } } }
						 */
				}
				WTPartMaster partB2Master = MyPartUtil.getWTPartMasterByNumber(newpartNumber);
				// 在ECO表单中判断BOM是否存在于未完成的ECO变更流程中
				boolean flag = false;
				WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();
				// ......................
				List<String> ecolist = ECOCRUDUtil.queryHistoryByNumber(effectNumber, eco.getNumber());
				if (ecolist.size() != 0) {
					result += "第" + rowNmuber + "行" + effectpartname + effectNumber + "已存在于未关闭的ECO变更流程中("
							+ ecolist.toString() + ")\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				QueryResult groupqrq = WTPartHelper.service.getUsesWTPartMasters(bompart);
				Map<String, WTPartUsageLink> linklist = new HashMap<String, WTPartUsageLink>();
				Map<String, WTPartUsageLink> linklist2 = new HashMap<String, WTPartUsageLink>();
				while (groupqrq.hasMoreElements()) {
					WTPartUsageLink puse = (WTPartUsageLink) groupqrq.nextElement();
					String number = ((WTPartMaster) puse.getRoleBObject()).getNumber();
					String linenumber = puse.getLineNumber().toString();
					linklist.put(number, puse);
					if (number.equals(partANumber)) {
						linklist2.put(linenumber, puse);
					}
				}
				// JSONObject obj2 = new JSONObject();
				if (linklist.containsKey(partANumber)) {
					// WTPartUsageLink puse = linklist.get(partANumber);
					/*
					 * WTPartMaster master = (WTPartMaster)
					 * puse.getRoleBObject(); partA =
					 * PartUtil.getLatestPartByPartMaster(master);
					 * partAlinenumber = puse.getLineNumber().toString();
					 * 
					 * // start WTCollection wtcol =
					 * WTPartHelper.service.getSubstituteLinks(puse);
					 * 
					 * WTPartSubstituteLink sublink =
					 * SubstituteLinkUtil.getSubstituteLink(partB1Master,
					 * wtcol); log.info("=========原替代料关系 1 ==========" +
					 * sublink); if (sublink == null) { result +=
					 * oldreplacepartname + oldpartNumber + "替换关系不存在;\r"; } else
					 * { if (sublink.getRoleBObject() instanceof WTPartMaster) {
					 * log.info("=========替代料关系  RoleB number ==========" +
					 * ((WTPartMaster) sublink.getRoleBObject()).getNumber()); }
					 * if (sublink.getQuantity().getAmount() != null) {
					 * oldpartamount =
					 * sublink.getQuantity().getAmount().toString(); }
					 * 
					 * }
					 */

					Iterator iter = linklist2.keySet().iterator();
					while (iter.hasNext()) {
						String linenumber = iter.next().toString();
						WTPartUsageLink link2 = linklist2.get(linenumber);

						WTPartMaster master = (WTPartMaster) link2.getRoleBObject();
						partA = PartUtil.getLatestPartByPartMaster(master);
						partAlinenumber = link2.getLineNumber().toString();

						// start
						WTCollection wtcol = WTPartHelper.service.getSubstituteLinks(link2);

						WTPartSubstituteLink sublink = SubstituteLinkUtil.getSubstituteLink(partB1Master, wtcol);
						log.info("=========原替代料关系 1 ==========" + sublink);
						if (sublink == null) {
							result += "第" + rowNmuber + "行" + oldreplacepartname + oldpartNumber + "替换关系不存在;\r";
							if (!errornumber.contains(rowNmuber)) {
								errornumber.add(rowNmuber);
							}
						} else {
							if (sublink.getRoleBObject() instanceof WTPartMaster) {
								log.info("=========替代料关系  RoleB number =========="
										+ ((WTPartMaster) sublink.getRoleBObject()).getNumber());
							}
							if (sublink.getQuantity().getAmount() != null) {
								oldpartamount = sublink.getQuantity().getAmount().toString();
							}

						}
						JSONObject obj2 = new JSONObject();
						obj2.put("effectnumber", effectNumber);
						obj2.put("effectstate", bompart.getState().getState().getDisplay(Locale.CHINA));
						obj2.put("effectunit", bompart.getDefaultUnit());

						obj2.put("view", view);
						if (partA != null) {
							obj2.put("partAstate", partA.getState().getState().getDisplay(Locale.CHINA));
						}

						obj2.put("partANumber", partANumber);
						obj2.put("partAlinenumber", partAlinenumber);
						obj2.put("oldpartnumber", oldpartNumber);
						obj2.put("oldpartamount", oldpartamount);
						if (partB1 != null) {
							obj2.put("oldunit", partB1.getDefaultUnit());
							obj2.put("oldstate", partB1.getState().getState().getDisplay(Locale.CHINA));

						}

						obj2.put("newpartnumber", newpartNumber);
						obj2.put("newpartamount", oldpartamount);
						if (partB2 != null) {
							obj2.put("newstate", partB2.getState().getState().getDisplay(Locale.CHINA));
							obj2.put("newunit", partB2.getDefaultUnit());
						}

						obj2.put("rowNmuber", rowNmuber);

						arraylist.put(obj2);

					}

				} else {
					result += "第" + rowNmuber + "行" + mainpartname + partANumber + "不存在于" + effectpartname
							+ effectNumber + "中;\r";
					if (!errornumber.contains(rowNmuber)) {
						errornumber.add(rowNmuber);
					}
				}
				/*
				 * obj2.put("effectnumber", effectNumber); obj2.put("view",
				 * view); obj2.put("partANumber", partANumber);
				 * obj2.put("partAlinenumber", partAlinenumber);
				 * obj2.put("oldpartnumber", oldpartNumber);
				 * obj2.put("oldpartamount", oldpartamount);
				 * obj2.put("newpartnumber", newpartNumber);
				 * obj2.put("newpartamount", oldpartamount);
				 * arraylist.put(obj2);
				 */
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				result += e.getMessage();
			}
		}
		try {
			object.put("tmcode", BOMHelp.correctcode);
			object.put("result", result);
			object.put("datalist", arraylist);
			object.put("errornumber", errornumber);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return object.toString();
	}

	public static WTPart getPart(String num, String ver, String viewName) throws Exception {
		if (viewName.equals(""))
			viewName = "Design";
		if (num == null || num.equals("") || num.trim().equals(""))
			return null;
		View view = ViewHelper.service.getView(viewName);
		WTPart part = null;
		QuerySpec qs = new QuerySpec(WTPart.class);
		SearchCondition sc = new SearchCondition(WTPart.class, WTPart.NUMBER, SearchCondition.EQUAL, num);
		qs.appendWhere(sc);
		sc = new SearchCondition(WTPart.class, "view.key.id", SearchCondition.EQUAL,
				view.getPersistInfo().getObjectIdentifier().getId());
		qs.appendAnd();
		qs.appendWhere(sc);
		if (!ver.equals("")) {
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.versionida2versioninfo"),
					SearchCondition.EQUAL, new KeywordExpression("'" + ver + "'")));
		}
		qs.appendAnd();
		qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
				new KeywordExpression("1")));

		qs.appendOrderBy(WTPart.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			part = (WTPart) qr.nextElement();
			OneOffVersionInfo one = part.getOneOffVersionInfo();
			OneOffVersionIdentifier id = one.getIdentifier();
			String valueOneOff = id.getValue();
			if (valueOneOff == null)
				return part;
		}
		return part;
	}

	/**
	 * 根据OID查询ECO 清单返回结果
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static String queryECO(String oid) {
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();
		String status = TMECOUtil.correctStatus;
		try {
			ReferenceFactory REF_FACTORY = new ReferenceFactory();
			WTChangeOrder2 eco = (WTChangeOrder2) REF_FACTORY.getReference(oid).getObject();

			// 根据ECO OID取ECO中变更的BOM
			List<BOMBean> beans = new ArrayList<BOMBean>();
			if (eco != null) {
				beans = ECOCRUDUtil.queryECOByECONumber(eco.getNumber());
			}
			for (BOMBean bean : beans) {
				JSONObject obj = new JSONObject();
				try {
					obj.put("", bean.getEffectnumber());
					obj.put("view", bean.getView());
					if (BOMBean.ADDPart.equals(bean.getType())) {
						obj.put("newAddNum", bean.getOldpartnumber());
						obj.put("amount", bean.getOldpartamount());
						obj.put("view", bean.getView());
						obj.put("effectnumber", bean.getEffectnumber());

					} else if (BOMBean.DelPart.equals(bean.getType())) {
						obj.put("partnumber", bean.getOldpartnumber());
						obj.put("linenumber", bean.getOldpartlinenumber());
						obj.put("effectnumber", bean.getEffectnumber());
						obj.put("view", bean.getView());

					} else if (BOMBean.ReplacePart.equals(bean.getType())) {
						obj.put("oldnumber", bean.getOldpartnumber());
						obj.put("oldlinenumber", bean.getOldpartlinenumber());
						obj.put("oldamount", bean.getOldpartamount());
						obj.put("newnumber", bean.getNewpartnumber());
						obj.put("newamount", bean.getNewpartlinenumber());
						obj.put("newlinenumber", bean.getNewpartamount());
						obj.put("effectnumber", bean.getEffectnumber());
						obj.put("view", bean.getView());

					} else if (BOMBean.UpdatePart.equals(bean.getType())) {
						obj.put("oldnumber", bean.getOldpartnumber());
						obj.put("oldlinenumber", bean.getOldpartlinenumber());
						obj.put("oldamount", bean.getOldpartamount());
						obj.put("newnumber", bean.getNewpartnumber());
						obj.put("newamount", bean.getNewpartlinenumber());
						obj.put("effectnumber", bean.getEffectnumber());
						obj.put("view", bean.getView());

					} else if (BOMBean.ADDReplcePart.equals(bean.getType())) {

					} else if (BOMBean.DelReplcePart.equals(bean.getType())) {

					} else if (BOMBean.UpdateReplcePart.equals(bean.getType())) {

					} else if (BOMBean.UpdateAPart.equals(bean.getType())) {

					} else if (BOMBean.ReplaceABPart.equals(bean.getType())) {

					}
					array.put(obj);
				} catch (Exception e) {
					status = TMECOUtil.errorStatus;
					e.printStackTrace();
				}
			}
			try {
				object.put("status", status);
				object.put("data", array);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return object.toString();
	}

	/**
	 * 获取关系中的部件
	 * 
	 * @param part
	 * @param list
	 * @return
	 */
	public static List<WTPart> getchildPart(WTPart part, List<WTPart> list) {
		try {
			QueryResult qs = WTPartHelper.service.getUsesWTPartMasters(part);
			while (qs.hasMoreElements()) {
				WTPartUsageLink link = (WTPartUsageLink) qs.nextElement();
				WTPartMaster master = (WTPartMaster) link.getRoleBObject();
				// WTPart childpart =
				// PartUtil.getLatestPartByPartMaster(master);
				WTPart childpart = getPart(master.getNumber(), "", part.getViewName());
				if (!list.contains(childpart)) {
					list.add(childpart);
				}
				if (childpart != null) {
					getchildPart(childpart, list);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 对部件对象升大版本
	 * 
	 * @param doc
	 * @return
	 */
	public static WTPart getNewVersionDoc(WTPart doc) {

		WTPart part = doc;
		log.info("doc ======" + IdentityFactory.getDisplayIdentifier(doc));
		Transaction tx = null;
		try {
			tx = new Transaction();
			tx.start();
			if (part == null) {
				return null;
			}
			WTContainer container = part.getContainer();
			WTContainerRef containerRef = WTContainerRef.newWTContainerRef(container); // container.getContainerReference();//
			TeamReference teamReference = part.getTeamId();
			Folder oldFoler = FolderHelper.getFolder(part);
			if (oldFoler == null) {
				String strLocation = part.getLocation();
				oldFoler = FolderHelper.service.getFolder(strLocation, containerRef);
			}

			part = (WTPart) wt.vc.VersionControlHelper.service.newVersion((wt.vc.Versioned) part);

			if (teamReference != null) {
				part.setTeamId(teamReference);
			}
			part.setContainer(container);

			FolderHelper.assignLocation((FolderEntry) part, oldFoler);

			part = (WTPart) PersistenceHelper.manager.save(part);
			part = (WTPart) PersistenceHelper.manager.refresh(part);

			tx.commit();
			tx = null;
		} catch (VersionControlException e) {

			e.printStackTrace();
		} catch (WTPropertyVetoException e) {

			e.printStackTrace();
		} catch (ObjectNoLongerExistsException e) {

			e.printStackTrace();
		} catch (WTException e) {

			e.printStackTrace();
		} finally {
			// 出现异常，事物回滚
			if (tx != null) {
				tx.rollback();
			}
		}

		log.info("wtdocument ======" + IdentityFactory.getDisplayIdentifier(part));
		return part;
	}

	/**
	 * 根据ECO编号返回ECO
	 * 
	 * @param changeOrderNumber
	 * @return
	 */
	public static WTChangeOrder2 getWTChangeOrder2ByNumber(String changeOrderNumber) {
		WTChangeOrder2 changeOrder = null;
		try {
			QuerySpec qs = new QuerySpec(WTChangeOrder2.class);
			qs.appendWhere(new SearchCondition(WTChangeOrder2.class, WTChangeOrder2.NUMBER, SearchCondition.EQUAL,
					changeOrderNumber), new int[] { 0 });
			QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
			while (qr.hasMoreElements()) {
				changeOrder = (WTChangeOrder2) qr.nextElement();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return changeOrder;
	}

	/**
	 * 获取父关系
	 * 
	 * @param wtpart
	 * @return
	 * @throws WTException
	 */
	public static List<WTPartUsageLink> getWTPartUsageLink(WTPart wtpart) throws WTException {
		List<WTPartUsageLink> set = new ArrayList<WTPartUsageLink>();
		QuerySpec qs = new QuerySpec(WTPartUsageLink.class);
		SearchCondition condition = new SearchCondition(WTPartUsageLink.class, "roleBObjectRef.key.id", "=",
				PersistenceHelper.getObjectIdentifier(wtpart.getMaster()).getId());
		qs.appendWhere(condition);
		qs.appendOrderBy(WTPartUsageLink.class, "thePersistInfo.createStamp", true);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			WTPartUsageLink link = (WTPartUsageLink) qr.nextElement();
			set.add(link);
		}
		return set;
	}

	/**
	 * 获取父关系
	 * 
	 * @param wtpart
	 * @return
	 * @throws WTException
	 */
	public static List<WTPart> getWTPartUsageLinkNew(WTPart wtpart) {
		List<WTPartUsageLink> set = new ArrayList<WTPartUsageLink>();
		List<WTPart> list = new ArrayList<WTPart>();
		WTPart part = null;
		QuerySpec qs;
		try {
			qs = new QuerySpec(WTPartUsageLink.class);

			SearchCondition condition = new SearchCondition(WTPartUsageLink.class, "roleBObjectRef.key.id", "=",
					PersistenceHelper.getObjectIdentifier(wtpart.getMaster()).getId());
			qs.appendWhere(condition);
			qs.appendOrderBy(WTPartUsageLink.class, "thePersistInfo.createStamp", true);
			QueryResult qr = PersistenceHelper.manager.find(qs);
			while (qr.hasMoreElements()) {
				WTPartUsageLink link = (WTPartUsageLink) qr.nextElement();
				set.add(link);

				part = (WTPart) link.getRoleAObject();

				wt.vc.VersionIdentifier vi = wt.vc.VersionControlHelper.nextVersionId(part);
				String v = vi.getValue();
				wt.part.WTPart p = ext.tianma.bom.eco.BOMHelp.getPart(part.getNumber(), v, part.getView().getName());
				if (null != p) {
					continue;
				}
				String version = VersionControlHelper.getIterationDisplayIdentifier(part).toString();
				// log.info("view:" + part.getViewName() + "===version:" +
				// version + "<br>");
				if (!list.contains(part)) {
					list.add(part);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public void test(String levol, List<String> list) {

		for (int i = 0; i < 4; i++) {
			levol = levol + "." + (i + 1);
			list.add(levol);
			if ("5.5".equals(levol)) {
				return;
			} else {
				test(levol, list);
			}
		}

	}

	/**
	 * 根据成品编号查询ECO变更清单 参数类型：str1
	 * 
	 * @param productNumber
	 * @return
	 * 
	 * 		{status:"",datalist[{econumber:"",createtime:"",creator:"",},{},{
	 *         }]}
	 */
	public static String searchECOData(String partNumber) {
		String result = "";
		// ECO查询结果返回值
		result = ecoResults(partNumber);
		return result;

	}

	/**
	 * 根据成品编号查询ECO清单返回结果
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static String ecoResults(String partNumber) {
		JSONObject object = new JSONObject();
		JSONArray array = new JSONArray();
		String status = TMECOUtil.correctStatus;
		// 根据成品编号搜索ECO变更清单
		List<ECOBean> beans = ECOCRUDUtil.searchECOData(partNumber);
		for (ECOBean bean : beans) {
			JSONObject obj = new JSONObject();
			try {
				String creator = "";
				String ecoView = "";
				String productState = "";
				if (!isNullOrEmpty(bean.getECONumber())) {
					try {
						WTChangeOrder2 eco = getWTChangeOrder2ByNumber(bean.getECONumber());
						creator = eco.getCreatorName();
						ecoView = bean.getECOView();
						WTPart part = CoreUtil.getWTPartByNumberAndView(partNumber, ecoView);
						productState = part.getState().getState().getDisplay(Locale.CHINA);// 状态
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				obj.put("partNumber", partNumber);
				obj.put("ecoView", ecoView);
				obj.put("productState", productState);
				obj.put("econumber", bean.getECONumber());
				obj.put("createtime", bean.getCreatetime());
				obj.put("creator", creator);
				array.put(obj);
			} catch (JSONException e) {
				status = TMECOUtil.errorStatus;
				e.printStackTrace();
			}
		}
		try {
			object.put("status", status);
			object.put("datalist", array);
		} catch (JSONException e) {
			e.printStackTrace();
		} finally {

		}
		return object.toString();
	}

	// 根据用户名查询WTUser对象
	public static WTUser getUserByName(String username) throws WTException {
		WTUser user = null;
		QuerySpec qs = new QuerySpec(WTUser.class);
		SearchCondition sc = new SearchCondition(WTUser.class, WTUser.NAME, "=", username);
		qs.appendWhere(sc);
		QueryResult qr = PersistenceHelper.manager.find(qs);
		while (qr.hasMoreElements()) {
			user = (WTUser) qr.nextElement();
		}
		return user;
	}
}
